<template>
  <avue-crud
    ref="crud"
    v-model="form"
    class="crud-table"
    :option="tableOption"
    :data="list"
    :page.sync="page"
    :search.sync="searchForm"
    :table-loading="loading"
    :header-cell-class-name="() => 'crud-table-head'"
    :cell-class-name="() => 'crud-cell'"
    @search-change="searchChange"
    @refresh-change="getList()"
    @current-change="currentChange"
    @size-change="handleSizeChange"
    @hook:mounted="$ele.tableMount($refs.crud)"
    @hook:beforeDestroy="$ele.tableDestroy($refs.crud)"
    @tree-load="treeLoad"
  >
    <template #searchMenu="{ size }">
      <el-button type="primary" :size="size" @click="searchChange">查 询</el-button>
      <el-button type="primary" plain :size="size" @click="resetForm">重 置</el-button>
    </template>
    <template #menuLeft="{ size }">
      <el-button type="primary" :size="size" @click="handleExcel">导出</el-button>
    </template>
    <template #menuRight="{ size }">
      <div class="all-panel">
        <span :key="index" v-for="(item, index) in zData">{{ item.name }}: {{ item.value }}</span>
      </div>
    </template>
  </avue-crud>
</template>
<script>
import { tableOption } from './tableOption'
import { warnProcessAnalysis, getShipList, getTenantList, warnProcessAnalysisByTenantId, warnProcessAnalysisTotal } from '@/api/warnmessage'

import { objFindDateArray2String } from '@/utils/util'
import { mapState } from 'vuex'

export default {
  data() {
    return {
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      list: [],
      loading: true,
      form: {},
      tenantArr: [],
      shipArr: [],
      zData: []
    }
  },
  computed: {
    ...mapState('user', ['tenantId']),
    tableOption() {
      return tableOption.call(this)
    }
  },
  created() {
    this.initDict()
  },
  methods: {
    getZdata() {
      const startTime = this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined
      const endTime = this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined
      warnProcessAnalysisTotal({ startTime, endTime }).then((res) => {
        const data = res.result || {}
        this.zData = [
          {
            name: '辖区告警总数',
            value: data.total
          },
          {
            name: '告警处理次数',
            value: data.process
          },
          // {
          //   name: '误报警次数',
          //   value: data.error
          // },
          {
            name: '处理闭环率',
            value: data.processCloseRate
          },
          // {
          //   name: '误报警率',
          //   value: data.errorRate
          // },
          {
            name: '处理及时率',
            value: data.processTimelyRate
          }
        ]
      })
    },
    formatterValue(value, dicCode, dic) {
      const res = dic || this.$store.getters['dict/getDictByCode'](dicCode)
      return (res.find((i) => i.value == value) && res.find((i) => i.value == value).lable) || value || '--'
    },
    resetForm() {
      this.$refs.crud.searchReset()
      this.page.currentPage = 1
      this.getList()
    },
    async initDict() {
      Promise.all([this.getTenant(), this.getShip()]).then(async () => {
        // 处理时间
        const time = this.$moment(new Date()).format('YYYY-MM-DD')
        this.searchForm.createTime = [time.slice(0, 4) + '-01-01' + ' 00:00:00', time + ' 23:59:59']
        this.getZdata()
        this.getList()
      })
    },

    getTenant() {
      this.searchForm.shipId = ''
      getTenantList({ superviseTenantId: this.tenantId }).then((res) => {
        if (res.result) {
          this.tenantArr = res.result.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        } else {
          this.tenantArr = []
        }
      })
    },
    getShip(value) {
      this.searchForm.shipId = ''
      getShipList({
        superviseTenantId: this.tenantId,
        tenantId: value || ''
      }).then((res) => {
        if (res.result) {
          this.shipArr = res.result.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        } else {
          this.shipArr = []
        }
      })
    },
    currentChange(val) {
      this.page.currentPage = val
      this.getList()
      this.$refs.curd?.doLayout()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getList()
      this.$refs.curd?.doLayout()
    },
    treeLoad(tree, treeNode, resolve) {
      warnProcessAnalysisByTenantId({
        ...this.searchForm,
        createTime: undefined,
        tenantId: tree.tenantId,
        startTime: this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined,
        endTime: this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined,
      }).then((res) => {
        resolve(res.result || [])
      })
    },
    getList() {
      this.loading = true
      const params = objFindDateArray2String({
        pageNumber: this.page.currentPage,
        pageSize: this.page.pageSize,
        ...this.searchForm,
        startTime: this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined,
        endTime: this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined,
        createTime: undefined
      })
      warnProcessAnalysis(params)
        .then((response) => {
          this.list = []
          this.page.total = 0
          this.$nextTick(() => {
            this.list = response.result.records
            this.page.total = response.result.total
          })
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
          this.$refs.crud?.doLayout()
        })
    },
    searchChange(form, done) {
      this.page.currentPage = 1
      this.getList(form || '')
      done && done()
    },
    handleExcel() {
      const params = {
        ...this.searchForm,
        createTime: undefined,
        startTime: this.searchForm.createTime?.length ? this.searchForm.createTime[0] : undefined,
        endTime: this.searchForm.createTime?.length ? this.searchForm.createTime[1] : undefined,
      }
      console.log("🤡 ~ params:", params)

      this.$http
        .request({
          url: '/warnings/warning/warnProcessAnalysisExport',
          method: 'get',
          params: params,
          responseType: 'blob' // 这里最重要,不要去掉
        })
        .then((res) => {
          const startTime = this.$moment(params.startTime).format('YYYY年MM月DD日')
          const endTime = this.$moment(params.endTime).format('YYYY年MM月DD日')
          this.downloadFileByBlob(res.data, params.startTime?`告警处理导出数据${startTime}-${endTime}.xls`:'告警处理导出数据.xls')
        })
    },
    // 导出
    downloadFileByBlob(blob, fileName = 'file') {
      const blobUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.download = fileName || 'defaultName'
      link.style.display = 'none'
      link.href = blobUrl
      // 触发点击
      document.body.appendChild(link)
      link.click()
      // 移除
      document.body.removeChild(link)
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .avue-crud__menu {
  flex-direction: column !important;
  .all-panel {
    margin-top: 14px;
    background: #a2bcdd;
    line-height: 36px;
    padding: 0 10px;
    color: #fff;
    > span {
      margin-right: 15px;
    }
  }
}
</style>
